package main 

import (
	"strconv"
	"time"
	"fmt"
	"code.google.com/p/odie"
)

var cancels = make(map[string]chan bool)

func handler(w *odie.ResponseWriter, req *odie.Request, vars odie.Context) {

	delay := vars.Get("delay")

	if delay == "" {
		return
	}

	d, err := strconv.Atoi(delay)

	if err != nil {
		fmt.Fprintf(w, "error: %s doesn't look like a number.", delay)
		return
	}

	cancels[req.Session] = make(chan bool)

	go func () {
		select {
		case <-time.After(time.Duration(d) * time.Second):
			fmt.Fprintf(w, "TIME! It has been %s seconds.", delay)
		case <-cancels[req.Session]:
			fmt.Fprintf(w, "Timer cancelled.")
		}
	} ()

	fmt.Fprintf(w, "OK.  Setting timer for %s seconds", delay)

	w.Suggest("cancel timer")
}

func cancelHandler(w *odie.ResponseWriter, req *odie.Request, vars odie.Context) {

	ch, ok := cancels[req.Session]

	if ok {
		ch <- true
	}
}

func init () {

	odie.Handle("set timer for $delay seconds", handler) 
	odie.Handle("remind me in $delay seconds", handler) 
	odie.Handle("notify me in $delay seconds", handler) 
	odie.Handle("cancel timer", cancelHandler) 
}

                
